﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Turtle8
{
    public partial class SearchCard : UserControl
    {
        SoldierCard sCard;
        SqlCommand selectGeneralCmd;
        SqlCommand selectColumnCmd;
        DataTable dt;

        public SearchCard(SoldierCard sCard)
        {
            InitializeComponent();
            this.Dock = DockStyle.Fill;

            this.sCard = sCard;
            
            string selectStr = CompanyManager.getSqlStringFromFile(@"\SELECT\SoldierDataSearchCard.SELECT.sql");
            selectGeneralCmd = SqlManager.SqlCommandFactory(selectStr);

            selectStr = CompanyManager.getSqlStringFromFile(@"\SELECT\SoldierColumnDataSearchCard.SELECT.sql");
            selectColumnCmd = SqlManager.SqlCommandFactory(selectStr);
            selectColumnCmd.Parameters.Add("@colNameVal", SqlDbType.NVarChar);

            dataGridView.Dock = DockStyle.Fill;
        }

        /// <summary>
        /// populates the dataGridView table on screeen
        /// </summary>
        private void initializeDataGridView(SqlCommand cmd)
        {
            if (dt != null)
                dt.Clear();
            dataGridView.DataSource = SqlManager.selectSqlQueryDataTable(cmd);
            dt = (DataTable)dataGridView.DataSource;

            if (dt.Rows.Count == 0)
                setEnabled(false, false, false, false);
            else setEnabled(false, false, true, true);

            comboBoxSearchCategory.Text = "בחר...";
            comboBoxSearchData.Text = "בחר...";

            //sets the column headers to hebrew
            CompanyManager.setTableColumnHeadersHebrew(dataGridView.Columns);
        }          
       
     
        private void buttonOpenSoldierCard_Click(object sender, EventArgs e)
        {
           // calculating the number of rows selected
            int selectedRowCount = dataGridView.Rows.GetRowCount(DataGridViewElementStates.Selected);
            int selectedRow = dataGridView.Rows.GetFirstRow(DataGridViewElementStates.Selected);
            
            string army_id = dataGridView.Rows[selectedRow].Cells["armyID"].FormattedValue.ToString();

           // only 1 row can be selected
            if (selectedRowCount > 0)
                sCard.changeMainPanel(SoldierCard.PanelState.OpenSoldierDataCard, army_id);
            else MessageBox.Show("על מנת לפתוח כרטיס לוחם, יש לסמן את השורה הרצויה");

        }

        private void comboBoxSearchCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            comboBoxSearchData.Items.Clear();
            comboBoxSearchData.Text = "בחר...";

            //populate dt with the relevant data.
            DataTable dt = SqlManager.selectSqlQueryDataTable(selectGeneralCmd);

            string selectedStr = CompanyManager.translateHebrewWord(comboBoxSearchCategory.Text);

           //this is the default case --->>> show all the soldiers in the company
            int col_index = dt.Columns.IndexOf(selectedStr);
            int row_ctr = dt.Rows.Count;

            switch (selectedStr)
            {
                case "all": 
                    comboBoxSearchData.Items.Clear();
                    buttonSearchSoldier.Enabled = true;
                    break;

                default:    
                        //adds an item to comboBoxSearchData. verifies no duplicates. no nulls.
                        for (int i = 0; i < row_ctr; i++)
                        {
                            try
                            {       
                                object obj;
                                if(selectedStr.Equals("platoon"))
                                    obj = (Byte)dt.Rows[i][col_index];
                                else obj = (string)dt.Rows[i][col_index];
                                if (!comboBoxSearchData.Items.Contains(obj) && !obj.Equals(string.Empty))
                                    comboBoxSearchData.Items.Add(dt.Rows[i][col_index]);
                            }
                            catch (Exception)
                            {
                                //do nothing. this exception is raised whenever there is a system.DBNull value. 
                                // we don't want to add this item to the ComboBox anyway!
                            }
                        }

                        //in case the platoon is null valued, 0 is inserted to the list --->>> remove it!
                        if (selectedStr.Equals("platoon"))
                            comboBoxSearchData.Items.Remove((Byte)0);

                        comboBoxSearchData.Enabled = true;
                        break;
            }
           

        }

        private void buttonSearchSoldier_Click(object sender, EventArgs e)
        {
            if (comboBoxSearchCategory.Text == "הכל")
                initializeDataGridView(selectGeneralCmd);
            else
            {

                string col_name = CompanyManager.translateHebrewWord(comboBoxSearchCategory.Text);
                if(col_name.Equals("armyID"))
                    col_name = "PersonalData." + col_name;

                selectColumnCmd.CommandText = selectColumnCmd.CommandText.Replace("[colNameKey]", col_name);
                selectColumnCmd.Parameters["@colNameVal"].Value = comboBoxSearchData.Text;
                initializeDataGridView(selectColumnCmd);
                selectColumnCmd.CommandText = CompanyManager.getSqlStringFromFile(@"\SELECT\SoldierColumnDataSearchCard.SELECT.sql");
            }
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            DialogResult result;
            result = MessageBox.Show("?האם אתה בטוח שברצונך למחוק כרטיס לוחם זה", "!שים לב", MessageBoxButtons.YesNo);

            if (result == DialogResult.Yes)
            {           
                int row_index = dataGridView.CurrentRow.Index;
                int col_index = dataGridView.Columns["armyID"].Index;
                string army_id = (string)dataGridView.Rows[row_index].Cells[col_index].Value;

                bool b = CompanyManager.deleteSoldier(army_id);
                sCard.refresh();
            }
        }

        /// <summary>
        /// sets comboBoxSearchCategory, buttonSearch, buttonDelete, buttonOpen, enabled properties.
        /// </summary>
        /// <param name="cbSearch"></param>
        /// <param name="btnSearch"></param>
        /// <param name="btnDelete"></param>
        /// <param name="btnOpen"></param>
        private void setEnabled(bool cbSearch, bool btnSearch, bool btnDelete, bool btnOpen)
        {
            comboBoxSearchData.Enabled = cbSearch;
            buttonSearchSoldier.Enabled = btnSearch;
            buttonDelete.Enabled = btnDelete;
            buttonOpenSoldierCard.Enabled = btnOpen;
        }

        private void comboBoxSearchData_SelectedIndexChanged(object sender, EventArgs e) { buttonSearchSoldier.Enabled = true; }
        private void SoldierDataSearchCard_Load(object sender, EventArgs e) {  initializeDataGridView(selectGeneralCmd); }

        public void refresh()
        {
            initializeDataGridView(selectGeneralCmd);
        }
    }

}
